//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Button, Card, Descriptions, List, message, Modal, Popover, Space, Table } from "antd";
import { useStores } from "@/hooks";
import type { ReviewInfo, ReviewResultItem, ReviewLinkItem } from "@/api/project_review";
import {
    get as get_review, remove_result,
    REVIEW_TYPE_BUG, REVIEW_TYPE_CODE, REVIEW_TYPE_FLOW, REVIEW_TYPE_MONTH, REVIEW_TYPE_PRODUCT, REVIEW_TYPE_QUARTER, REVIEW_TYPE_TEST,
    LINK_TYPE_CONTENT,
    LINK_TYPE_REQUIREMENT,
    LINK_TYPE_BUG,
    LINK_TYPE_TASK,
    LINK_TYPE_TEST_CASE,
    remove_link,
    LINK_TYPE_SPRIT,
    LINK_TYPE_DOC,
    LINK_TYPE_PAGES,
    LINK_TYPE_API_COLL,
    LINK_TYPE_DRAW
} from "@/api/project_review";
import { request } from "@/utils/request";
import { DeleteOutlined, EditOutlined, MoreOutlined, PlusOutlined } from "@ant-design/icons";
import UserPhoto from "@/components/Portrait/UserPhoto";
import EditReviewResultModal from "./components/EditReviewResultModal";
import moment from "moment";
import AddReviewLinkModal from "./components/AddReviewLinkModal";
import type { ColumnsType } from 'antd/lib/table';
import { useHistory } from "react-router-dom";
import { LinkBugInfo, LinkEntryInfo, LinkRequirementInfo, LinkTaskInfo, LinkTestCaseInfo } from "@/stores/linkAux";
import { useTranslation } from "react-i18next";


const ReviewDetail = () => {
    const history = useHistory();
    const { t } = useTranslation();

    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');
    const linkAuxStore = useStores('linkAuxStore');

    const [reviewInfo, setReviewInfo] = useState<ReviewInfo | null>(null);

    const [showAddResultModal, setShowAddResultModal] = useState(false);

    const [updateResultItem, setUpdateResultItem] = useState<ReviewResultItem | null>(null);
    const [removeResultItem, setRemoveResultItem] = useState<ReviewResultItem | null>(null);

    const [showAddLinkModal, setShowAddLinkModal] = useState(false);

    const [removeLinkItem, setRemoveLinkItem] = useState<ReviewLinkItem | null>(null);

    const loadReviewInfo = async () => {
        const res = await get_review({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            review_id: projectStore.curReview?.review_id ?? "",
        });
        setReviewInfo(res.review);
    };

    const removeResult = async () => {
        if (projectStore.curReview == null || removeResultItem == null) {
            return;
        }
        await request(remove_result({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            review_id: projectStore.curReview.review_id,
            result_id: removeResultItem.result_id,
        }));
        message.info(t("text.removeSuccess"));
        setRemoveResultItem(null);
        await loadReviewInfo();
    };

    const removeLink = async () => {
        if (projectStore.curReview == null || removeLinkItem == null) {
            return;
        }
        await request(remove_link({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            review_id: projectStore.curReview.review_id,
            link_id: removeLinkItem.link_id,
        }));
        message.info(t("text.removeSuccess"));
        setRemoveLinkItem(null);
        await loadReviewInfo();
    };

    const columns: ColumnsType<ReviewLinkItem> = [
        {
            title: t("text.cate"),
            width: 80,
            render: (_, row: ReviewLinkItem) => {
                if (row.link_type == LINK_TYPE_CONTENT) {
                    return t("project.link.type.content");
                } else if (row.link_type == LINK_TYPE_REQUIREMENT) {
                    return t("project.link.type.requirement");
                } else if (row.link_type == LINK_TYPE_BUG) {
                    return t("project.link.type.bug");
                } else if (row.link_type == LINK_TYPE_TASK) {
                    return t("project.link.type.task");
                } else if (row.link_type == LINK_TYPE_TEST_CASE) {
                    return t("project.link.type.testcase");
                } else if (row.link_type == LINK_TYPE_SPRIT) {
                    return t("project.link.type.workplan");
                } else if (row.link_type == LINK_TYPE_DOC) {
                    return t("project.link.type.doc");
                } else if (row.link_type == LINK_TYPE_PAGES) {
                    return t("project.link.type.pages");
                } else if (row.link_type == LINK_TYPE_API_COLL) {
                    return t("project.link.type.apiColl");
                } else if (row.link_type == LINK_TYPE_DRAW) {
                    return t("project.link.type.draw");
                }
                return "";
            },
        },
        {
            title: t("text.title"),
            render: (_, row: ReviewLinkItem) => (
                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    if (row.link_type == LINK_TYPE_CONTENT) {
                        linkAuxStore.goToLink(new LinkEntryInfo("", projectStore.curProjectId, row.link_target_id), history);
                    } else if (row.link_type == LINK_TYPE_REQUIREMENT) {
                        linkAuxStore.goToLink(new LinkRequirementInfo("", projectStore.curProjectId, row.link_target_id), history);
                    } else if (row.link_type == LINK_TYPE_BUG) {
                        linkAuxStore.goToLink(new LinkBugInfo("", projectStore.curProjectId, row.link_target_id), history);
                    } else if (row.link_type == LINK_TYPE_TASK) {
                        linkAuxStore.goToLink(new LinkTaskInfo("", projectStore.curProjectId, row.link_target_id), history);
                    } else if (row.link_type == LINK_TYPE_TEST_CASE) {
                        linkAuxStore.goToLink(new LinkTestCaseInfo("", projectStore.curProjectId, row.link_target_id), history);
                    }
                }}>{row.link_title}</Button>
            ),
        },
        {
            title: t("text.operation"),
            width: 40,
            render: (_, row: ReviewLinkItem) => (
                <Popover placement="bottom" trigger="click" content={
                    <Space direction="vertical">
                        <Button type="link" danger disabled={!(projectStore.isAdmin && !projectStore.isClosed)} icon={<DeleteOutlined />}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveLinkItem(row);
                            }}>{t("text.remove")}</Button>
                    </Space>
                }>
                    <MoreOutlined />
                </Popover>
            ),
        }
    ];

    useEffect(() => {
        if (projectStore.curProjectId != "" && projectStore.curReview != null) {
            loadReviewInfo();
        }
    }, [projectStore.curProjectId, projectStore.curReview]);

    return (
        <>
            <Descriptions bordered column={1} labelStyle={{ width: "100px" }}>
                <Descriptions.Item label={t("text.cate")}>
                    {projectStore.curReview?.review_type == REVIEW_TYPE_CODE && t("project.review.cate.code")}
                    {projectStore.curReview?.review_type == REVIEW_TYPE_FLOW && t("project.review.cate.flow")}
                    {projectStore.curReview?.review_type == REVIEW_TYPE_PRODUCT && t("project.review.cate.product")}
                    {projectStore.curReview?.review_type == REVIEW_TYPE_BUG && t("project.review.cate.bug")}
                    {projectStore.curReview?.review_type == REVIEW_TYPE_TEST && t("project.review.cate.test")}
                    {projectStore.curReview?.review_type == REVIEW_TYPE_MONTH && t("project.review.cate.month")}
                    {projectStore.curReview?.review_type == REVIEW_TYPE_QUARTER && t("project.review.cate.quarter")}
                </Descriptions.Item>
                <Descriptions.Item label={t("project.review.releateMember")}>
                    <Space style={{ flexWrap: "wrap" }}>
                        {projectStore.curReview?.member_list.map(memberItem => (
                            <Space key={memberItem.member_user_id} style={{ backgroundColor: "#eee", padding: "2px 10px", borderRadius: "6px" }}>
                                <UserPhoto logoUri={memberItem.member_logo_uri} style={{ width: "20px", borderRadius: "10px" }} />
                                {memberItem.member_display_name}
                            </Space>
                        ))}
                    </Space>
                </Descriptions.Item>
                <Descriptions.Item label={t("text.desc")}>
                    <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word", paddingLeft: "10px" }}>{projectStore.curReview?.desc ?? ""}</pre>
                </Descriptions.Item>
                <Descriptions.Item label={t("project.review.createTime")}>
                    {moment(projectStore.curReview?.create_time).format("YYYY-MM-DD HH:mm")}
                </Descriptions.Item>
            </Descriptions>
            {reviewInfo != null && (
                <Card title={<h3 style={{ fontSize: "16px", fontWeight: 700 }}>{t("project.review.result")}</h3>} bordered={false}
                    extra={<>
                        {projectStore.isAdmin && !projectStore.isClosed && (
                            <Button type="link" icon={<PlusOutlined />} title={t("project.review.addResult")} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowAddResultModal(true);
                            }} />
                        )}
                    </>}>
                    <List rowKey="result_id" dataSource={reviewInfo.result_list} pagination={false}
                        renderItem={(resultItem, resultIndex) => (
                            <List.Item extra={<>
                                {projectStore.isAdmin && !projectStore.isClosed && (
                                    <Popover placement="bottom" trigger="click" content={
                                        <Space direction="vertical">
                                            <Button type="link" icon={<EditOutlined />} onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setUpdateResultItem(resultItem);
                                            }}>{t("text.update")}</Button>
                                            <Button type="link" icon={<DeleteOutlined />} danger onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setRemoveResultItem(resultItem);
                                            }}>{t("text.remove")}</Button>
                                        </Space>
                                    }>
                                        <MoreOutlined />
                                    </Popover>
                                )}
                            </>}>
                                <div style={{ display: "flex" }}>
                                    <span>{resultIndex + 1}.</span>
                                    <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word", paddingLeft: "10px" }}>{resultItem.content}</pre>
                                </div>
                            </List.Item>
                        )} />
                </Card>
            )}

            {reviewInfo != null && (
                <Card title={<h3 style={{ fontSize: "16px", fontWeight: 700 }}>{t("project.review.releateLink")}</h3>} bordered={false}
                    extra={<>
                        {projectStore.isAdmin && !projectStore.isClosed && (
                            <Button type="link" icon={<PlusOutlined />} title={t("project.review.addLink")} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowAddLinkModal(true);
                            }} />
                        )}
                    </>}>
                    <Table rowKey="link_id" dataSource={reviewInfo.link_list} columns={columns} pagination={false} />
                </Card>
            )}


            {showAddResultModal == true && projectStore.curProject !== undefined && reviewInfo != null && (
                <EditReviewResultModal reviewInfo={reviewInfo} projectInfo={projectStore.curProject}
                    onCancel={() => setShowAddResultModal(false)}
                    onOk={() => {
                        setShowAddResultModal(false);
                        loadReviewInfo();
                    }} />
            )}
            {updateResultItem != null && projectStore.curProject !== undefined && reviewInfo != null && (
                <EditReviewResultModal resultItem={updateResultItem} reviewInfo={reviewInfo} projectInfo={projectStore.curProject}
                    onCancel={() => setUpdateResultItem(null)}
                    onOk={() => {
                        setUpdateResultItem(null);
                        loadReviewInfo();
                    }} />
            )}
            {removeResultItem != null && (
                <Modal open title={t("project.review.removeResult")} mask={false}
                    okText={t("text.remove")} okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveResultItem(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeResult();
                    }}>
                    {t("project.review.removeResultMsg")}
                    <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word", maxHeight: "100px", overflowY: "scroll" }}>{removeResultItem.content}</pre>
                </Modal>
            )}
            {showAddLinkModal == true && projectStore.curProject !== undefined && reviewInfo != null && (
                <AddReviewLinkModal reviewInfo={reviewInfo} projectInfo={projectStore.curProject}
                    onCacel={() => setShowAddLinkModal(false)}
                    onOk={() => {
                        setShowAddLinkModal(false);
                        loadReviewInfo();
                    }} />
            )}
            {removeLinkItem != null && (
                <Modal open title={t("project.review.removeLink")} mask={false}
                    okText={t("text.remove")} okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveLinkItem(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeLink();
                    }}>
                    {t("project.review.removeLinkMsg", { name: removeLinkItem.link_title })}
                </Modal>
            )}
        </>
    );
};

export default observer(ReviewDetail);